//
//  OYEmotionTools.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/10.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit

// 沙盒存储路径
let documentPath = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!) as NSString).appendingPathComponent("recentEmotion.archiver")
class OYEmotionTools: NSObject {

    let numberOfPages: Int = 20
    /// 单例对象
    static let sharedTools:OYEmotionTools = OYEmotionTools()

     // MARK: -私有化构造方法，禁止外界调用
    private override init() {
        super.init()

    }

    
     // MARK: -数组懒加载
    lazy var allEmotionArr:[[[OYEmotionModel]]] = {
        
        return [self.recentEmotionArr,self.defaultEmotionArr,self.emojiEmotionArr,self.lxhEmotionArr]
    }()
    
    lazy var recentEmotionArr:[[OYEmotionModel]] = {
        // 先从沙盒中加载最近表情，如果沙盒中有就是用沙盒中的最近表情
        if let localArr = self.loadRecentEmotion(){
            return localArr
        }else {
            var recentArr = [[OYEmotionModel]]()
            recentArr.append([OYEmotionModel]())
            return recentArr
        }
    }()
    
    lazy var defaultEmotionArr:[[OYEmotionModel]] = {
        return self.generateTowdimensionalArray(resource:"default",numberOfPages:20)
    }()
    
    lazy var emojiEmotionArr:[[OYEmotionModel]] = {
        return self.generateTowdimensionalArray(resource:"emoji",numberOfPages:20)
    }()
    
    lazy var lxhEmotionArr:[[OYEmotionModel]] = {
        return self.generateTowdimensionalArray(resource:"lxh",numberOfPages:20)
    }()
    
    
    /// 最近表情
    ///
    /// - Parameter emotionModel: 表情键盘中点击选中的当前表情
    func addRecentEmotion(emotionModel:OYEmotionModel) {
        // 遍历三维表情模型数组中的最近数组，判断当前模型是否在数组中
        for (i,currentEmotionModel) in recentEmotionArr[0].enumerated() {
            if currentEmotionModel == emotionModel {
                // 如果存在当前表情，将当前表情从数组中删除，然后添加至首位
                recentEmotionArr[0].remove(at: i)
            }
        }
        recentEmotionArr[0].insert(emotionModel, at: 0)
        // 如果当前表情数组中的表情已经等于21，则删除最后一个元素
        if recentEmotionArr.count == 21 {
            recentEmotionArr.removeLast()
        }
        
        // 更新表情数据源
        allEmotionArr[0][0] = recentEmotionArr[0]
        
        // 将更新后的数据归档至沙盒
        NSKeyedArchiver.archiveRootObject(recentEmotionArr, toFile: documentPath)
        
    }
    
     // MARK: -解档沙盒中的最近表情
    func loadRecentEmotion () -> [[OYEmotionModel]]?{
        let recentEmotionArr = NSKeyedUnarchiver.unarchiveObject(withFile: documentPath) as? [[OYEmotionModel]]
        return recentEmotionArr
    }
    
    /// 将每种表情的二维模型数组合并产生一个三维模型表情数组
    ///
    /// - Returns: 三维模型表情数组
     func generateThreeDimensionalArray() -> [[[OYEmotionModel]]] {
        
        var emotionArr:[[[OYEmotionModel]]] = [[[OYEmotionModel]]]()
        
        // 创建一个最近常用数组，先不放置元素
        let recentModelArr = [OYEmotionModel]()
        var recentArr:[[OYEmotionModel]] = [[OYEmotionModel]]()
        recentArr.append(recentModelArr)
       
        emotionArr.append(recentArr)
        emotionArr.append(generateTowdimensionalArray(resource: "default", numberOfPages: 20))
        emotionArr.append(generateTowdimensionalArray(resource: "emoji", numberOfPages: 20))
        emotionArr.append(generateTowdimensionalArray(resource: "lxh", numberOfPages: 20))
        
        return emotionArr
        
    }
    
    
    /// 根据模型数组将数组内模型分页构建二维模型数组
    ///
    /// - Parameters:
    ///   - resource: plist文件名
    ///   - numberOfPages: 分页每页页数
    /// - Returns: 返回二维模型数组，的每一个元素为20个model的一维数组
    private func generateTowdimensionalArray(resource:String,numberOfPages:Int) -> [[OYEmotionModel]] {
        // 获取从plist加载的一维数组
        let emotionModelArr = setupEmotionModelArr(resoruce: resource)
        // 创建一个二维数组，它的元素是一维表情模型数组
        var emotionArr:[[OYEmotionModel]]  = [[OYEmotionModel]]()
        // 确定当前表情数组的页数
        let page = (emotionModelArr.count - 1) / numberOfPages + 1
        // 遍历数组，截取数组，将截取的数组加入二维数组中
        for i in 0..<page {
            let loc:Int = numberOfPages * i
            var len:Int = numberOfPages
            if i == page - 1 {
                // 如果是最后一页
                len = emotionModelArr.count - numberOfPages * i
            }
            let range:NSRange = NSRange(location:loc,length:len)
            let tempArr:[OYEmotionModel] = (emotionModelArr as NSArray).subarray(with: range) as! [OYEmotionModel]
            emotionArr.append(tempArr)
        }
      
        return emotionArr
    }
    
    /// 根据文件名获取表情模型数组
    ///
    /// - Parameter resouce: plist文件名(不用写后缀)
    private func setupEmotionModelArr(resoruce:String) -> [OYEmotionModel] {
        // 获取Emoticons.bundle文件的路径
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
        // 获取Emoticons bundle对象
        let bundle = Bundle(path: path!)
        // 获取bundle对象中需要的文件路径(可以跨两个文件夹)
        let emotionPlistPath = bundle?.path(forResource: resoruce + "/info.plist", ofType: nil)
        // 将plist文件转为字典数组
        let plistArr:[[String:Any]] = NSArray(contentsOfFile: emotionPlistPath!) as! [[String:Any]]
        // 将字典数组转换为模型数组
        let modelArr:[OYEmotionModel] = NSArray.yy_modelArray(with: OYEmotionModel.self, json: plistArr) as![OYEmotionModel]
        
        for model in modelArr {
            // 为模型中添加的path属性赋值
            if model.type == "0" {
                let bundlePath = bundle?.path(forResource: resoruce, ofType: nil)
                model.path =  bundlePath! + "/" + model.png!
            }
        }
        return modelArr
    }
}
